package com.elitedatai.mchtest.flyer.controller;

import com.dji.sdk.common.HttpResultResponse;
import com.dji.sdk.common.PaginationData;
import com.elitedatai.mchtest.flyer.model.dto.FlyerDTO;
import com.elitedatai.mchtest.flyer.service.IFlyerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * 飞手控制器
 * 提供飞手管理的增删改查REST API接口
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/flyers")
@Validated
public class FlyerController {

    @Autowired
    private IFlyerService flyerService;

    /**
     * 创建飞手
     * @param flyerDTO 飞手数据传输对象
     * @return 创建的飞手信息
     */
    @PostMapping
    public HttpResultResponse<FlyerDTO> createFlyer(@Valid @RequestBody FlyerDTO flyerDTO) {
        try {
            FlyerDTO createdFlyer = flyerService.createFlyer(flyerDTO);
            return HttpResultResponse.success(createdFlyer);
        } catch (Exception e) {
            log.error("创建飞手失败", e);
            return HttpResultResponse.error("创建飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID更新飞手信息
     * @param id 飞手主键ID
     * @param flyerDTO 飞手数据传输对象
     * @return 更新后的飞手信息
     */
    @PutMapping("/{id}")
    public HttpResultResponse<FlyerDTO> updateFlyerById(@PathVariable @NotNull Long id, 
                                                        @Valid @RequestBody FlyerDTO flyerDTO) {
        try {
            Optional<FlyerDTO> updatedFlyer = flyerService.updateFlyerById(id, flyerDTO);
            return updatedFlyer.map(HttpResultResponse::success)
                    .orElse(HttpResultResponse.error("飞手不存在"));
        } catch (Exception e) {
            log.error("更新飞手失败", e);
            return HttpResultResponse.error("更新飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据飞手ID更新飞手信息
     * @param flyerId 飞手业务ID
     * @param flyerDTO 飞手数据传输对象
     * @return 更新后的飞手信息
     */
    @PutMapping("/flyer-id/{flyerId}")
    public HttpResultResponse<FlyerDTO> updateFlyerByFlyerId(@PathVariable @NotBlank String flyerId, 
                                                             @Valid @RequestBody FlyerDTO flyerDTO) {
        try {
            Optional<FlyerDTO> updatedFlyer = flyerService.updateFlyerByFlyerId(flyerId, flyerDTO);
            return updatedFlyer.map(HttpResultResponse::success)
                    .orElse(HttpResultResponse.error("飞手不存在"));
        } catch (Exception e) {
            log.error("更新飞手失败", e);
            return HttpResultResponse.error("更新飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID删除飞手
     * @param id 飞手主键ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public HttpResultResponse<Void> deleteFlyerById(@PathVariable @NotNull Long id) {
        try {
            boolean deleted = flyerService.deleteFlyerById(id);
            return deleted ? HttpResultResponse.success() : HttpResultResponse.error("飞手不存在");
        } catch (Exception e) {
            log.error("删除飞手失败", e);
            return HttpResultResponse.error("删除飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据飞手ID删除飞手
     * @param flyerId 飞手业务ID
     * @return 删除结果
     */
    @DeleteMapping("/flyer-id/{flyerId}")
    public HttpResultResponse<Void> deleteFlyerByFlyerId(@PathVariable @NotBlank String flyerId) {
        try {
            boolean deleted = flyerService.deleteFlyerByFlyerId(flyerId);
            return deleted ? HttpResultResponse.success() : HttpResultResponse.error("飞手不存在");
        } catch (Exception e) {
            log.error("删除飞手失败", e);
            return HttpResultResponse.error("删除飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询飞手信息
     * @param id 飞手主键ID
     * @return 飞手信息
     */
    @GetMapping("/{id}")
    public HttpResultResponse<FlyerDTO> getFlyerById(@PathVariable @NotNull Long id) {
        try {
            Optional<FlyerDTO> flyer = flyerService.getFlyerById(id);
            return flyer.map(HttpResultResponse::success)
                    .orElse(HttpResultResponse.error("飞手不存在"));
        } catch (Exception e) {
            log.error("查询飞手失败", e);
            return HttpResultResponse.error("查询飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据飞手ID查询飞手信息
     * @param flyerId 飞手业务ID
     * @return 飞手信息
     */
    @GetMapping("/flyer-id/{flyerId}")
    public HttpResultResponse<FlyerDTO> getFlyerByFlyerId(@PathVariable @NotBlank String flyerId) {
        try {
            Optional<FlyerDTO> flyer = flyerService.getFlyerByFlyerId(flyerId);
            return flyer.map(HttpResultResponse::success)
                    .orElse(HttpResultResponse.error("飞手不存在"));
        } catch (Exception e) {
            log.error("查询飞手失败", e);
            return HttpResultResponse.error("查询飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据姓名查询飞手信息
     * @param flyerName 飞手姓名
     * @return 飞手信息列表
     */
    @GetMapping("/name/{flyerName}")
    public HttpResultResponse<List<FlyerDTO>> getFlyersByName(@PathVariable @NotBlank String flyerName) {
        try {
            List<FlyerDTO> flyers = flyerService.getFlyersByName(flyerName);
            return HttpResultResponse.success(flyers);
        } catch (Exception e) {
            log.error("查询飞手失败", e);
            return HttpResultResponse.error("查询飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据状态查询飞手信息
     * @param status 飞手状态
     * @return 飞手信息列表
     */
    @GetMapping("/status/{status}")
    public HttpResultResponse<List<FlyerDTO>> getFlyersByStatus(@PathVariable @NotNull Integer status) {
        try {
            List<FlyerDTO> flyers = flyerService.getFlyersByStatus(status);
            return HttpResultResponse.success(flyers);
        } catch (Exception e) {
            log.error("查询飞手失败", e);
            return HttpResultResponse.error("查询飞手失败: " + e.getMessage());
        }
    }

    /**
     * 查询所有飞手信息
     * @return 飞手信息列表
     */
    @GetMapping
    public HttpResultResponse<List<FlyerDTO>> getAllFlyers() {
        try {
            List<FlyerDTO> flyers = flyerService.getAllFlyers();
            return HttpResultResponse.success(flyers);
        } catch (Exception e) {
            log.error("查询飞手失败", e);
            return HttpResultResponse.error("查询飞手失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询所有飞手信息
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @return 分页飞手信息
     */
    @GetMapping("/page")
    public HttpResultResponse<Page<FlyerDTO>> getFlyersWithPagination(
            @RequestParam(defaultValue = "0") @Min(0) int page,
            @RequestParam(defaultValue = "10") @Min(1) int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<FlyerDTO> flyerPage = flyerService.getAllFlyers(pageable);
            
            return HttpResultResponse.success(flyerPage);
        } catch (Exception e) {
            log.error("分页查询飞手失败", e);
            return HttpResultResponse.error("分页查询飞手失败: " + e.getMessage());
        }
    }

    /**
     * 根据状态分页查询飞手信息
     * @param status 飞手状态
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @return 分页飞手信息
     */
    @GetMapping("/status/{status}/page")
    public HttpResultResponse<Page<FlyerDTO>> getFlyersByStatusWithPagination(
            @PathVariable @NotNull Integer status,
            @RequestParam(defaultValue = "0") @Min(0) int page,
            @RequestParam(defaultValue = "10") @Min(1) int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<FlyerDTO> flyerPage = flyerService.getFlyersByStatus(status, pageable);
            
            return HttpResultResponse.success(flyerPage);
        } catch (Exception e) {
            log.error("分页查询飞手失败", e);
            return HttpResultResponse.error("分页查询飞手失败: " + e.getMessage());
        }
    }

    /**
     * 多条件搜索飞手
     * @param flyerId 飞手业务ID
     * @param flyerName 飞手姓名
     * @param status 状态
     * @param qualificationType 资质类型
     * @param certificationLevel 认证等级
     * @return 符合条件的飞手列表
     */
    @GetMapping("/search")
    public HttpResultResponse<List<FlyerDTO>> searchFlyers(
            @RequestParam(required = false) String flyerId,
            @RequestParam(required = false) String flyerName,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String qualificationType,
            @RequestParam(required = false) String certificationLevel) {
        try {
            List<FlyerDTO> flyers = flyerService.getFlyersByMultipleConditions(
                    flyerId, flyerName, status, qualificationType, certificationLevel);
            return HttpResultResponse.success(flyers);
        } catch (Exception e) {
            log.error("搜索飞手失败", e);
            return HttpResultResponse.error("搜索飞手失败: " + e.getMessage());
        }
    }

    /**
     * 检查飞手ID是否存在
     * @param flyerId 飞手业务ID
     * @return 是否存在
     */
    @GetMapping("/exists/flyer-id/{flyerId}")
    public HttpResultResponse<Boolean> existsByFlyerId(@PathVariable @NotBlank String flyerId) {
        try {
            boolean exists = flyerService.existsByFlyerId(flyerId);
            return HttpResultResponse.success(exists);
        } catch (Exception e) {
            log.error("检查飞手ID是否存在失败", e);
            return HttpResultResponse.error("检查飞手ID是否存在失败: " + e.getMessage());
        }
    }

    /**
     * 检查电话是否存在
     * @param phone 联系电话
     * @return 是否存在
     */
    @GetMapping("/exists/phone/{phone}")
    public HttpResultResponse<Boolean> existsByPhone(@PathVariable @NotBlank String phone) {
        try {
            boolean exists = flyerService.existsByPhone(phone);
            return HttpResultResponse.success(exists);
        } catch (Exception e) {
            log.error("检查电话是否存在失败", e);
            return HttpResultResponse.error("检查电话是否存在失败: " + e.getMessage());
        }
    }

    /**
     * 检查邮箱是否存在
     * @param email 邮箱地址
     * @return 是否存在
     */
    @GetMapping("/exists/email/{email}")
    public HttpResultResponse<Boolean> existsByEmail(@PathVariable @NotBlank String email) {
        try {
            boolean exists = flyerService.existsByEmail(email);
            return HttpResultResponse.success(exists);
        } catch (Exception e) {
            log.error("检查邮箱是否存在失败", e);
            return HttpResultResponse.error("检查邮箱是否存在失败: " + e.getMessage());
        }
    }

    /**
     * 更新飞手状态
     * @param flyerId 飞手业务ID
     * @param status 新状态
     * @return 更新结果
     */
    @PatchMapping("/flyer-id/{flyerId}/status")
    public HttpResultResponse<Void> updateFlyerStatus(@PathVariable @NotBlank String flyerId, 
                                                      @RequestParam @NotNull Integer status) {
        try {
            boolean updated = flyerService.updateFlyerStatus(flyerId, status);
            return updated ? HttpResultResponse.success() : HttpResultResponse.error("飞手不存在");
        } catch (Exception e) {
            log.error("更新飞手状态失败", e);
            return HttpResultResponse.error("更新飞手状态失败: " + e.getMessage());
        }
    }

    /**
     * 增加飞行时长
     * @param flyerId 飞手业务ID
     * @param hours 增加的飞行时长（小时）
     * @return 更新结果
     */
    @PatchMapping("/flyer-id/{flyerId}/flight-hours")
    public HttpResultResponse<Void> addFlightHours(@PathVariable @NotBlank String flyerId, 
                                                   @RequestParam @NotNull BigDecimal hours) {
        try {
            boolean updated = flyerService.addFlightHours(flyerId, hours);
            return updated ? HttpResultResponse.success() : HttpResultResponse.error("飞手不存在");
        } catch (Exception e) {
            log.error("增加飞行时长失败", e);
            return HttpResultResponse.error("增加飞行时长失败: " + e.getMessage());
        }
    }

    /**
     * 增加任务次数
     * @param flyerId 飞手业务ID
     * @param missions 增加的任务次数
     * @return 操作结果
     */
    @PatchMapping("/flyer-id/{flyerId}/missions")
    public HttpResultResponse<Void> addMissions(@PathVariable @NotBlank String flyerId, 
                                                @RequestParam @NotNull Integer missions) {
        try {
            boolean success = flyerService.addMissions(flyerId, missions);
            return success ? HttpResultResponse.success() : HttpResultResponse.error("操作失败");
        } catch (Exception e) {
            log.error("增加任务次数失败", e);
            return HttpResultResponse.error("增加任务次数失败: " + e.getMessage());
        }
    }

    /**
     * 增加事故次数
     * @param flyerId 飞手业务ID
     * @param accidents 增加的事故次数
     * @return 操作结果
     */
    @PatchMapping("/flyer-id/{flyerId}/accidents")
    public HttpResultResponse<Void> addAccidents(@PathVariable @NotBlank String flyerId, 
                                                 @RequestParam @NotNull Integer accidents) {
        try {
            boolean success = flyerService.addAccidents(flyerId, accidents);
            return success ? HttpResultResponse.success() : HttpResultResponse.error("操作失败");
        } catch (Exception e) {
            log.error("增加事故次数失败", e);
            return HttpResultResponse.error("增加事故次数失败: " + e.getMessage());
        }
    }

    /**
     * 增加违规次数
     * @param flyerId 飞手业务ID
     * @param violations 增加的违规次数
     * @return 操作结果
     */
    @PatchMapping("/flyer-id/{flyerId}/violations")
    public HttpResultResponse<Void> addViolations(@PathVariable @NotBlank String flyerId, 
                                                  @RequestParam @NotNull Integer violations) {
        try {
            boolean success = flyerService.addViolations(flyerId, violations);
            return success ? HttpResultResponse.success() : HttpResultResponse.error("操作失败");
        } catch (Exception e) {
            log.error("增加违规次数失败", e);
            return HttpResultResponse.error("增加违规次数失败: " + e.getMessage());
        }
    }

    /**
     * 计算并更新安全评级
     * @param flyerId 飞手业务ID
     * @return 操作结果
     */
    @PatchMapping("/flyer-id/{flyerId}/safety-rating")
    public HttpResultResponse<Void> calculateAndUpdateSafetyRating(@PathVariable @NotBlank String flyerId) {
        try {
            boolean success = flyerService.calculateAndUpdateSafetyRating(flyerId);
            return success ? HttpResultResponse.success() : HttpResultResponse.error("操作失败");
        } catch (Exception e) {
            log.error("计算安全评级失败", e);
            return HttpResultResponse.error("计算安全评级失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新飞手状态
     * @param flyerIds 飞手业务ID列表
     * @param status 新状态
     * @return 更新结果
     */
    @PatchMapping("/batch/status")
    public HttpResultResponse batchUpdateFlyerStatus(@RequestParam List<String> flyerIds,
                                                           @RequestParam @NotNull Integer status) {
        try {
            int updatedCount = flyerService.batchUpdateFlyerStatus(flyerIds, status);
            return HttpResultResponse.success("成功更新 " + updatedCount + " 个飞手的状态");
        } catch (Exception e) {
            log.error("批量更新飞手状态失败", e);
            return HttpResultResponse.error("批量更新飞手状态失败: " + e.getMessage());
        }
    }
}